import {
  Button,
  Card,
  Col,
  Form,
  Input,
  Row,
  Image,
  Space,
  Select,
  DatePicker,
  message,
} from 'antd';
import Table, { ColumnsType } from 'antd/es/table';
import { TableRowSelection } from 'antd/es/table/interface';
import { useEffect, useState } from 'react';

import commonService from '@/api/services/commonService';
import { useCommon } from '@/hooks/common';
import sizePrintLayoutEditor from '@/myFabric/sizePrintLayoutEditor';
// import { toFen, toYuan } from '@/utils/format-number';

// import DetailModal from './detail';

const statusMap: any = {
  0: '未打印',
  1: '已打印',
};

const printAreaOptions: any = [
  { label: 'front', value: 'front' },
  { label: 'back', value: 'back' },
  { label: 'double', value: 'double' },
];

// const statusOptions = Object.keys(statusMap).map((key) => {
//   return { label: statusMap[key], value: key };
// });

export default function ProducePage() {
  const uri = 'erp-order-view';
  const cateName = '生产订单管理';
  const {
    data = {},
    // ModalPros,
    searchForm,
    onSearchFormReset,
    onSearch,
    handleChange,
    // refetch,
  } = useCommon({ orderNumber: '', userId: '', status: '', print: 0 }, uri, {
    loginName: '',
    id: 0,
    userName: '',
    userType: '',
    phoneNumber: ''
  });

  // const [showDetail, setShowDetail] = useState(false);
  // const [detail, setDetail] = useState<any>({});
  const [base, setBase] = useState<any>({});
  const [picked, setPicked] = useState<any>([]);
  const [dates, setDates] = useState<any>([]);

  //打印中
  const [printing, setPrinting] = useState(false);
  // 打印全部中
  const [printalling, setPrintalling] = useState(false);

  useEffect(() => {
    commonService.getCustomApi('/common/baseProperty/getAllProperty', {}).then((res) => {
      setBase(res);
    });
  }, []);

  // 导出全部未打印
  const printAll = async () => {
    setPrintalling(true);
    //查询全部未打印的订单
    const res = await commonService.getCustomApi('/admin/erp-order-view/page', { print: 0, pageSize: 999999, pageNo: 1 });
    // 生成打印文件并下载下来
    await sizePrintLayoutEditor.downNoPrintOrderGoods(res.list);

    console.log(res);

    // 更新打印状态
    // const ids = res.list.map((item: any) => item.id);
    // await commonService.postCustomApi('/admin/erp-order-view/updatePrintStatus', { orderDetailIds: ids.join(",") });
    // const values = searchForm.getFieldsValue();
    // onSearch(values);
    setPrintalling(false);
  }

  const toPrint = async () => {
    if (!picked.length) {
      message.error('请选择要打印的订单！');
      return;
    }

    setPrinting(true);

    const ids = picked.map((item: any) => {
      return item.id;
    });

    // 生成打印文件并下载下来
    await sizePrintLayoutEditor.downNoPrintOrderGoods(picked);

    // 更新打印状态
    // await commonService.postCustomApi('/admin/erp-order-view/updatePrintStatus', { orderDetailIds: ids.join(",") });
    // const values = searchForm.getFieldsValue();
    // onSearch(values);
    setPrinting(false);
  };

  // const doClose = (id: string) => {
  //   commonService.postCustomApi(`/admin/order/closeOrder?orderId=${id}`, {}).then((res) => {
  //     refetch();
  //   });
  // };

  // const toDetail = (orderNumber: string) => {
  //   commonService.getCustomApi('/admin/order/orderDetail', { orderNumber }).then((res) => {
  //     setDetail(res);
  //     setShowDetail(true);
  //   });
  // };

  const onRangePickerChange = (date: any, dateString: any) => {
    setDates(date);
    searchForm.setFieldsValue({ startTime: dateString?.[0] || '', endTime: dateString?.[1] || '' });
  };

  const handleReset = () => {
    setDates([]);
    onSearchFormReset();
  };

  const columns: ColumnsType<any> = [
    { title: '订单编号', dataIndex: 'orderNumber', align: 'center', width: 160 },
    { title: '商品名称', dataIndex: 'title', align: 'center', width: 160 },
    {
      title: '图片', dataIndex: 'thumbnail', align: 'center', width: 160, render: (val) => {
        return (
          <div className='flex gap-[6px]'>
            <Image src={JSON.parse(val || '[]')[0]} alt="图片1" />
            <Image src={JSON.parse(val || '[]')[1]} alt="图片2" />
          </div>
        );
      }
    },
    { title: '尺寸', dataIndex: 'size', align: 'center', width: 60 },
    { title: '数量', dataIndex: 'num', align: 'center', width: 60 },
    { title: '底板编号', dataIndex: 'ppId', align: 'center', width: 120 },
    { title: '订单时间', dataIndex: 'createTime', align: 'center', width: 180 },
    {
      title: '是否打印',
      dataIndex: 'print',
      align: 'center',
      width: 120,
      render: (status) => <div>{statusMap[status]}</div>,
    },
    // {
    //   title: '操作',
    //   key: 'operation',
    //   align: 'center',
    //   width: 100,
    //   fixed: 'right',
    //   render: (_, record) => (
    //     <div className="flex flex-col gap-[10px] w-full justify-center text-gray">
    //       {record.status === 0 ? <><Popconfirm
    //         title="确认删除该数据？"
    //         okText="确定"
    //         cancelText="取消"
    //         placement="left"
    //         onConfirm={() => doClose(record.id)}
    //       >
    //         <Button>关闭订单</Button>
    //       </Popconfirm>
    //       <Button onClick={() => onEdit(record)}>修改价格</Button></> : ''}
    //       <Button onClick={() => toDetail(record.orderNumber)}>订单详情</Button>
    //     </div>
    //   ),
    // },
  ];

  // rowSelection objects indicates the need for row selection
  const rowSelection: TableRowSelection<any> = {
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
    onSelect: (record, selected, selectedRows) => {
      setPicked(selectedRows);
      console.log(record, selected, selectedRows);
    },
    onSelectAll: (selected, selectedRows, changeRows) => {
      setPicked(selectedRows);
      console.log(selected, selectedRows, changeRows);
    },
  };

  return (
    <Space direction="vertical" size="large" className="w-full">
      <Card>
        <Form form={searchForm} onFinish={onSearch}>
          <Form.Item<any> name="startTime" style={{ display: 'none' }}>
            <Input type="hidden" />
          </Form.Item>
          <Form.Item<any> name="endTime" style={{ display: 'none' }}>
            <Input type="hidden" />
          </Form.Item>
          <Row gutter={[16, 16]}>
            <Col span={8} lg={6}>
              <Form.Item<any> label="订单编号" name="orderNumber" className="!mb-0">
                <Input />
              </Form.Item>
            </Col>
            <Col span={8} lg={6}>
              <Form.Item<any> label="底板编号" name="ppId" className="!mb-0">
                <Input />
              </Form.Item>
            </Col>
            <Col span={8} lg={6}>
              <Form.Item<any> label="供应商" name="supplier" className="!mb-0">
                <Select options={base.supplier?.map((item: any) => {
                  return { label: item, value: item };
                })} />
              </Form.Item>
            </Col>
            <Col span={8} lg={6}>
              <Form.Item<any> label="材质" name="material" className="!mb-0">
                <Select options={base.material?.map((item: any) => {
                  return { label: item, value: item };
                })} />
              </Form.Item>
            </Col>
            <Col span={8} lg={6}>
              <Form.Item<any> label="面料" name="materialName" className="!mb-0">
                <Select options={base.materialName?.map((item: any) => {
                  return { label: item, value: item };
                })} />
              </Form.Item>
            </Col>
            <Col span={8} lg={6}>
              <Form.Item<any> label="工艺" name="technology" className="!mb-0">
                <Select options={base.technology?.map((item: any) => {
                  return { label: item.name, value: item.value };
                })} />
              </Form.Item>
            </Col>
            <Col span={8} lg={6}>
              <Form.Item<any> label="门幅宽" name="fabricDoorWidth" className="!mb-0">
                <Input suffix="CM" />
              </Form.Item>
            </Col>
            <Col span={8} lg={6}>
              <Form.Item<any> label="印刷方式" name="fillType" className="!mb-0">
                <Select options={base.printType?.map((item: any) => {
                  return { label: item.name, value: item.value };
                })} />
              </Form.Item>
            </Col>
            <Col span={8} lg={8}>
              <Form.Item<any> label="订单起始时间" className="!mb-0">
                <DatePicker.RangePicker value={dates} onChange={onRangePickerChange} />
              </Form.Item>
            </Col>
            <Col span={8} lg={6}>
              <Form.Item<any> label="是否已打印" name="print" className="!mb-0">
                <Select options={Object.keys(statusMap)?.map((item: any) => {
                  return { label: statusMap[item], value: item };
                })} />
              </Form.Item>
            </Col>
            <Col span={8} lg={6}>
              <Form.Item<any> label="印刷区域" name="printArea" className="!mb-0">
                <Select options={printAreaOptions} />
              </Form.Item>
            </Col>
            <Col span={24} lg={12}>
              <div className="flex justify-end">
                <Button onClick={handleReset}>重置</Button>
                <Button type="primary" htmlType="submit" className="ml-4">
                  查询
                </Button>
              </div>
            </Col>
          </Row>
        </Form>
      </Card>

      <Card
        title={cateName}
        extra={
          <div className="flex flex-row gap-[10px]">

            <Button
              type="primary"
              loading={printalling}
              onClick={printAll}
            >
              导出全部未打印
            </Button>
            &nbsp;
            &nbsp;
            &nbsp;
            <Button
              type="primary"
              loading={printing}
              onClick={() =>
                toPrint()
              }
            >
              导出选中的订单
            </Button>
          </div>
        }
      >
        <Table
          rowKey="id"
          size="small"
          pagination={{ total: data.totalCount }}
          scroll={{ x: 'max-content' }}
          columns={columns}
          dataSource={data.list}
          rowSelection={{ ...rowSelection }}
          onChange={handleChange}
        />
      </Card>

      {/* <CommonModal {...ModalPros} /> */}
      {/* <DetailModal onOk={() => setShowDetail(false)} onCancel={() => setShowDetail(false)} showDetail={showDetail} detail={detail} /> */}
    </Space>
  );
}

// function CommonModal({ title, show, formValue, onOk, onCancel }: any) {
//   const [form] = Form.useForm();
//   useEffect(() => {
//     form.setFieldsValue({ ...formValue, finalPrice: toYuan(formValue.finalPrice) });
//   }, [formValue, form]);

//   const handleOk = () => {
//     const params = { ...formValue, ...form.getFieldsValue() };
//     params.finalPrice = toFen(params.finalPrice);
//     onOk(params);
//   };
//   return (
//     <Modal
//       title={title}
//       open={show}
//       onOk={() => handleOk()}
//       onCancel={onCancel}
//     >
//       <Form
//         initialValues={formValue}
//         form={form}
//         labelCol={{ span: 4 }}
//         wrapperCol={{ span: 18 }}
//         layout="horizontal"
//       >
//         <Form.Item<any> label="价格" name="finalPrice" required>
//           <InputNumber suffix="元" />
//         </Form.Item>
//       </Form>
//     </Modal>
//   );
// }
